package cn.hxth.dubbo.service.impl;

import cn.hxth.api.model.Remind;
import cn.hxth.api.query.PageResult;
import cn.hxth.api.query.QueryObject;
import cn.hxth.api.service.IRemindService;
import cn.hxth.api.util.SplitUtil;
import cn.hxth.dubbo.service.mapper.RemindMapper;
import cn.hxth.dubbo.service.mq.RabbitMQSender;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class RemindServiceImpl implements IRemindService {
    @Resource
    private RabbitMQSender rabbitMQSender ;
    @Resource
    private RemindMapper remindMapper ;
    @Resource(name = "myRedisTemplate")
    private RedisTemplate<String,Object> redisTemplate ;
    @Override
    public boolean deleteRemind(int sid) {
        boolean flag = this.remindMapper.deleteBySid(sid)>0;
        if(flag){
           this.rabbitMQSender.send("data-change-queue","{\"event_type\": \"delete\", \"data_type\": \"remind\", \"sid\": " + sid +   "}");
        }
        return flag ;
    }
    public  boolean insertRemind(Remind remind){
        remind.setDate(new Date());
        boolean flag = this.remindMapper.insert(remind)>0 ;
        if(flag){
            this.rabbitMQSender.send("data-change-queue","{\"event_type\": \"add\", \"data_type\": \"remind\", \"sid\": " + remind.getSpec().getSid() +   "}");
        }
        return  true ;
    }

    @Override
    public boolean updateCountBySid(Remind remind) {
        return this.remindMapper.updateCount(remind) ;
    }

    @Override
    public boolean updateRemind(Remind remind) {
        remind.setDate(new Date());
        boolean flag = this.remindMapper.updateByPrimaryKey(remind)>0 ;
        if(flag){
            this.rabbitMQSender.send("data-change-queue","{\"event_type\": \"update\", \"data_type\": \"remind\", \"sid\": " + remind.getRid() +   "}");
        }
        return  true ;
    }
    @Override
    public PageResult findAll(QueryObject queryObject){

        int count = this.remindMapper.selectCountAll(queryObject) ;
        List<Object> remindList = this.redisTemplate.opsForHash().values("remindList") ;
        if (remindList.size()>0){
            /*for(Object o:remindList){
               //o =o.toString();
               System.out.println(o);
            }*/
            List<Object> listData = SplitUtil.splitList(remindList, queryObject.getCurrentPage(), queryObject.getPageSize());
            return  new PageResult(listData,count,queryObject.getCurrentPage(),queryObject.getPageSize()) ;
        }
        List<Remind> listData = this.remindMapper.selectAll(queryObject);
        return  new PageResult(listData,count,queryObject.getCurrentPage(),queryObject.getPageSize()) ;
    }

    @Override
    public Remind getRemindBySid(int sid) {
        return  this.remindMapper.selectBySid(sid) ;
    }
}
